@workover/mcp 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +24 -4
  2. package/index.mjs +79 -27
  3. package/lib.mjs +276 -14
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -11,21 +11,31 @@ npm i -g @workover/cli
11
11
  workover login
12
12
  ```
13
13
 
14
- Then add the server to Claude Code:
14
+ Then add the server to Claude Code, for every project (`--scope user`; without it the server is
15
+ only available in the directory you ran the command in):
15
16
 
16
17
  ```sh
17
- claude mcp add workover -- npx -y @workover/mcp
18
+ claude mcp add --scope user workover -- npx -y @workover/mcp@latest
19
+ workover install-claude # optional: a skill that points Claude Code at Workover links
18
20
  ```
19
21
 
20
22
  That's it. Ask Claude Code things like *"read my Workover doc about onboarding and tighten the intro"* — it reads the document and its proposed changes appear in Workover as tracked-change **suggestions** you accept or reject.
21
23
 
22
24
  ## Tools
23
25
 
26
+ **Every tool that takes a `docId` takes the document's link.** Pass the URL the person pasted
27
+ (`https://workover.io/app/<workspace>/docs/<id>`, anything after it is ignored), the UUID at the end
28
+ of it, or the numeric id. `url` and `doc` are accepted as names for it too. A link the signed-in
29
+ account cannot open comes back as "not found, or no access"; a `workover.dev` link used with a
30
+ production sign-in names the environment instead.
31
+
24
32
  - `workover_search_docs(query)` — find documents by title/content
25
33
  - `workover_read_doc(docId, tabId?)` — read a document's text, with the style guide attached
26
34
  - `workover_list_projects()` — list your projects
27
35
  - `workover_create_doc(projectId, title, markdown, categories?)` — create a document with its content written in, filed under the categories you name (a category that does not exist yet is created)
28
36
  - `workover_upload_image(docId, path, alt)` — put a local image into a document's media
37
+ - `workover_list_images(docId, tabId?)` — the images in a document: file name, alt text and src
38
+ - `workover_set_image(docId, src, filename?, alt?)` — set an image's file name (its WordPress media name) and/or alt text, as the editor's Edit image dialog does. Needs `workover login --write`
29
39
  - `workover_propose_edit(docId, markdown, note, tabId?, reasoning?)` — propose a revised version (rendered as suggestions; never applied or published automatically)
30
40
  - `workover_edit_doc(docId, markdown, note, tabId?)` — edit a document directly, no review step. Needs `workover login --write`
31
41
  - `workover_style_guide(projectId?)` — the rules this team writes by
@@ -33,7 +43,7 @@ That's it. Ask Claude Code things like *"read my Workover doc about onboarding a
33
43
  - `workover_list_tabs(docId)` — a document's tabs
34
44
  - `workover_create_tab(docId, title, parentId?)` — add an empty tab. Needs `workover login --write`
35
45
 
36
- Everything the MCP server can do, the CLI can do too (`workover doc create|read|propose|write|list|search|tabs|tab-new`, `workover rules list|export|add`). That is deliberate: a newly-registered MCP server is not available in the session that registered it, so an agent that finds mid-task that it needs Workover has no way in until it restarts. A CLI subcommand works immediately.
46
+ Everything the MCP server can do, the CLI can do too (`workover doc create|read|propose|write|list|search|tabs|tab-new|images|image`, `workover rules list|export|add`). That is deliberate: a newly-registered MCP server is not available in the session that registered it, so an agent that finds mid-task that it needs Workover has no way in until it restarts. A CLI subcommand works immediately.
37
47
 
38
48
  ## The style guide
39
49
 
@@ -66,6 +76,14 @@ tab**, so `workover_read_doc` says which tab it read and what the others are, an
66
76
  an optional `tabId`. Creating a tab needs `--write`; deleting one, and changing which tab syncs to
67
77
  WordPress, stay in the browser.
68
78
 
79
+ ## Images
80
+
81
+ `workover_set_image` changes one image without rewriting the document: the alt text is set on every
82
+ copy of that image, in every tab, directly in the live document (the `<img alt>` that publishing
83
+ reads), and the file name on the image's media record, which WordPress gets on the next publish.
84
+ Whichever of the two is left out is kept. It needs `--write`, like any other direct edit, and the
85
+ document's activity records it as you, via the agent.
86
+
69
87
  ## Safety
70
88
 
71
89
  The server authenticates with the token from `workover login`. By default it is **read + propose only**: it cannot publish to WordPress, change your account, or apply changes without you. Every edit is a suggestion you accept, and only a person publishes. Revoke access anytime in **Workover → Settings → Developer**.
@@ -87,7 +105,9 @@ made by an agent is never indistinguishable from one you typed.
87
105
 
88
106
  ## Configuration
89
107
 
90
- The API endpoint comes from your `workover login` (defaults to `https://api.workover.io`).
108
+ The API endpoint comes from your `workover login` (defaults to `https://api.workover.io`). The
109
+ sign-in is read on every call, so `workover login` takes effect without restarting the client.
110
+ `WORKOVER_CONFIG` names a different sign-in file, as in the CLI.
91
111
 
92
112
  ## Usage data
93
113
 
package/index.mjs CHANGED
@@ -19,24 +19,44 @@ import {
19
19
  telemetryEnabled,
20
20
  } from './telemetry.mjs';
21
21
 
22
+ // The CLI's sign-in file. WORKOVER_CONFIG names another one (a second environment), as in the CLI.
23
+ const CONFIG_FILE = process.env.WORKOVER_CONFIG || join(homedir(), '.workover', 'config.json');
24
+
22
25
  function loadAuth() {
23
26
  try {
24
- const cfg = JSON.parse(readFileSync(join(homedir(), '.workover', 'config.json'), 'utf8'));
27
+ const cfg = JSON.parse(readFileSync(CONFIG_FILE, 'utf8'));
25
28
  return validAuth(cfg);
26
29
  } catch {
27
30
  return null; // not signed in
28
31
  }
29
32
  }
30
33
 
34
+ /**
35
+ * The sign-in is read per call, not once at start-up.
36
+ *
37
+ * Read once, a server started before `workover login` stayed signed out until Claude Code was
38
+ * restarted, so "run workover login" was advice that did not work in the session that got it. The
39
+ * file is a few hundred bytes; reading it per tool call costs nothing next to the request itself.
40
+ */
31
41
  const auth = loadAuth();
32
- const { api, apiPost } = makeApi({ auth: auth ?? { api: '', token: '' } });
33
- const dispatch = makeDispatch({ auth, api, apiPost, readFile: readFileSync });
42
+ const dispatch = (name, args) => {
43
+ const current = loadAuth();
44
+ const { api, apiPost } = makeApi({ auth: current ?? { api: '', token: '' } });
45
+ return makeDispatch({ auth: current, api, apiPost, readFile: readFileSync })(name, args);
46
+ };
47
+
48
+ /** The schema for a document argument. Every tool that names a document takes all three forms. */
49
+ const DOC_ARG = {
50
+ type: ['string', 'number'],
51
+ description:
52
+ 'The document: its link exactly as the person gave it (https://workover.io/app/<workspace>/docs/<id>, or workover.dev for staging), the UUID at the end of that link, or the numeric id ("#12345" → 12345).',
53
+ };
34
54
 
35
55
  const TOOLS = [
36
56
  {
37
57
  name: 'workover_search_docs',
38
58
  description:
39
- 'Search your Workover documents by title and content. Returns matching documents with their ids — use workover_read_doc to read one.',
59
+ 'Search your Workover documents by title and content. Returns matching documents with their ids — use workover_read_doc to read one. Not needed when you already have a document link: pass that to workover_read_doc.',
40
60
  inputSchema: {
41
61
  type: 'object',
42
62
  properties: { query: { type: 'string', description: 'What to search for.' } },
@@ -46,15 +66,11 @@ const TOOLS = [
46
66
  {
47
67
  name: 'workover_read_doc',
48
68
  description:
49
- "Read the full text of a Workover document by its id. The result also carries the workspace's style guide and, for a document with tabs, says which tab you are reading and what the others are.",
69
+ "Read the full text of a Workover document. Pass the document link the person pasted (workover.io/app/<workspace>/docs/<id>) as docId, as it is; a UUID or numeric id works too. The result also carries the workspace's style guide and, for a document with tabs, says which tab you are reading and what the others are.",
50
70
  inputSchema: {
51
71
  type: 'object',
52
72
  properties: {
53
- docId: {
54
- type: 'number',
55
- description:
56
- 'The numeric document id, as printed by workover_search_docs ("#12345" → 12345). Not the handle from a document URL.',
57
- },
73
+ docId: DOC_ARG,
58
74
  tabId: {
59
75
  type: 'number',
60
76
  description:
@@ -112,7 +128,7 @@ const TOOLS = [
112
128
  inputSchema: {
113
129
  type: 'object',
114
130
  properties: {
115
- docId: { type: 'number', description: 'The numeric document id.' },
131
+ docId: DOC_ARG,
116
132
  },
117
133
  required: ['docId'],
118
134
  },
@@ -124,7 +140,7 @@ const TOOLS = [
124
140
  inputSchema: {
125
141
  type: 'object',
126
142
  properties: {
127
- docId: { type: 'number', description: 'The numeric document id.' },
143
+ docId: DOC_ARG,
128
144
  title: { type: 'string', description: 'The tab title.' },
129
145
  parentId: {
130
146
  type: 'number',
@@ -171,10 +187,7 @@ const TOOLS = [
171
187
  inputSchema: {
172
188
  type: 'object',
173
189
  properties: {
174
- docId: {
175
- type: 'number',
176
- description: 'The numeric id of the document the image belongs to (not a URL handle).',
177
- },
190
+ docId: DOC_ARG,
178
191
  path: { type: 'string', description: 'Local file path to the image (png/jpg/webp).' },
179
192
  alt: { type: 'string', description: 'Alt text describing the image.' },
180
193
  },
@@ -182,16 +195,55 @@ const TOOLS = [
182
195
  },
183
196
  },
184
197
  {
185
- name: 'workover_edit_doc',
198
+ name: 'workover_list_images',
186
199
  description:
187
- "Edit a Workover document DIRECTLY, replacing its body with no suggestions for anyone to review. Use this ONLY when the person has asked for the change to be made — working together on a document they have open, 'just make that edit'. Otherwise use workover_propose_edit, which is the default and leaves them something to accept or reject. Read the document first (workover_read_doc) and provide the FULL revised document: this REPLACES the body, so anything omitted is deleted. Requires a token from `workover login --write`; without that scope this returns a permission error and proposing is the way through. Never publishes to WordPress.",
200
+ "List the images in a Workover document, in reading order, with each one's file name (the name WordPress gets on publish), its alt text, and its src. Use it before workover_set_image, and to find images with no alt text.",
188
201
  inputSchema: {
189
202
  type: 'object',
190
203
  properties: {
191
- docId: {
204
+ docId: DOC_ARG,
205
+ tabId: {
192
206
  type: 'number',
193
- description: 'The numeric id of the document to edit (not a URL handle).',
207
+ description:
208
+ 'Which tab, for a document with tabs (workover_list_tabs). Omit for the main body.',
209
+ },
210
+ },
211
+ required: ['docId'],
212
+ },
213
+ },
214
+ {
215
+ name: 'workover_set_image',
216
+ description:
217
+ "Set an image's file name and/or alt text in a Workover document, as the editor's \"Edit image\" dialog does. The alt text is written onto every copy of the image in the document (what publishing reads); the file name becomes the WordPress media name on the next publish. Whichever you leave out is kept. Write a short, specific kebab-case file name and alt text that says what the image shows. Requires a token from `workover login --write`. Never publishes.",
218
+ inputSchema: {
219
+ type: 'object',
220
+ properties: {
221
+ docId: DOC_ARG,
222
+ src: {
223
+ type: 'string',
224
+ description: 'The image src, exactly as workover_list_images printed it.',
225
+ },
226
+ filename: {
227
+ type: 'string',
228
+ description:
229
+ 'The new file name, e.g. "lifterlms-groups-admin-list". The extension is kept if you leave it off.',
194
230
  },
231
+ alt: {
232
+ type: 'string',
233
+ description: 'The new alt text. An empty string clears it.',
234
+ },
235
+ },
236
+ required: ['docId', 'src'],
237
+ },
238
+ },
239
+ {
240
+ name: 'workover_edit_doc',
241
+ description:
242
+ "Edit a Workover document DIRECTLY, replacing its body with no suggestions for anyone to review. Use this ONLY when the person has asked for the change to be made — working together on a document they have open, 'just make that edit'. Otherwise use workover_propose_edit, which is the default and leaves them something to accept or reject. Read the document first (workover_read_doc) and provide the FULL revised document: this REPLACES the body, so anything omitted is deleted. Requires a token from `workover login --write`; without that scope this returns a permission error and proposing is the way through. Never publishes to WordPress.",
243
+ inputSchema: {
244
+ type: 'object',
245
+ properties: {
246
+ docId: DOC_ARG,
195
247
  markdown: {
196
248
  type: 'string',
197
249
  description:
@@ -217,11 +269,7 @@ const TOOLS = [
217
269
  inputSchema: {
218
270
  type: 'object',
219
271
  properties: {
220
- docId: {
221
- type: 'number',
222
- description:
223
- 'The numeric id of the document to propose changes to (not a URL handle).',
224
- },
272
+ docId: DOC_ARG,
225
273
  markdown: {
226
274
  type: 'string',
227
275
  description: 'The complete revised document as markdown (not just the changed parts).',
@@ -250,7 +298,7 @@ const telemetry = telemetryEnabled(process.env, { auth });
250
298
  // Keep in step with package.json. It is what every telemetry event is stamped with, so a stale
251
299
  // value here does not break anything — it quietly attributes this release's behaviour to an older
252
300
  // one, which is worse, because the numbers still look fine.
253
- const VERSION = '0.8.1';
301
+ const VERSION = '0.10.0';
254
302
 
255
303
  /**
256
304
  * What the client is told about this server before it calls anything.
@@ -270,6 +318,10 @@ const VERSION = '0.8.1';
270
318
  */
271
319
  const INSTRUCTIONS = `Workover holds this team's documents and their STYLE GUIDE.
272
320
 
321
+ A Workover document link (https://workover.io/app/<workspace>/docs/<id>) is a document reference:
322
+ pass it as docId to any tool here, unchanged. Never call the Workover API yourself or read the
323
+ token file.
324
+
273
325
  Before writing or revising anything here, call workover_style_guide for the project you are
274
326
  writing for, and follow every rule it returns. Those rules are the team's house style — spelling
275
327
  variant, punctuation, banned words, tone — and writing that ignores them has to be corrected by
@@ -335,7 +387,7 @@ function report(tool, startedAt, ok, errorKind) {
335
387
  }),
336
388
  // The API attributes the event to whoever this token belongs to. Nothing here nominates an
337
389
  // identity, because a client that could would be a client that could claim somebody else's.
338
- { auth },
390
+ { auth: loadAuth() },
339
391
  );
340
392
  }
341
393
 
package/lib.mjs CHANGED
@@ -129,6 +129,185 @@ export const renderStyleFeedback = (style) => {
129
129
  return `\n\n${style.summary}`;
130
130
  };
131
131
 
132
+ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
133
+ const FULL_UUID_RE = new RegExp(`^${UUID_RE.source}$`, 'i');
134
+
135
+ /**
136
+ * Which document somebody meant, from whatever they pasted.
137
+ *
138
+ * 1234 / #1234 → { id: 1234 }
139
+ * https://workover.io/app/pellio/docs/<uuid> → { handle, host, workspace }
140
+ * …/docs/<uuid>/anything?tab=3#heading, workover.dev, → the same, with that host
141
+ * a preview host, or no scheme at all
142
+ * https://workover.io/app/projects/1234 → { id: 1234, host } (the old editor URL)
143
+ * <uuid> on its own → { handle }
144
+ *
145
+ * Returns null for anything else. The URL is what people paste because it is what the browser shows
146
+ * them, and on 2026-10-16 an agent handed one went digging through the source to turn it into a row
147
+ * id. Every command that names a document takes all of these, so nobody has to.
148
+ *
149
+ * `host` is kept so a link to one environment opened with a sign-in for another can be named as
150
+ * that, rather than reported as a missing document (see `environmentMismatch`).
151
+ */
152
+ export const docRef = (value) => {
153
+ // Trim the wrapping that pasted links arrive in: <angle brackets>, quotes, a trailing full stop.
154
+ const s = String(value ?? '')
155
+ .trim()
156
+ .replace(/^[<"'([]+/, '')
157
+ .replace(/[>"')\].,;]+$/, '');
158
+ if (!s) return null;
159
+ const id = rowId(s);
160
+ if (id !== null) return { id };
161
+ if (FULL_UUID_RE.test(s)) return { handle: s.toLowerCase() };
162
+
163
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(s);
164
+ if (hasScheme || /^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?\//i.test(s)) {
165
+ let url;
166
+ try {
167
+ url = new URL(hasScheme ? s : `https://${s}`);
168
+ } catch {
169
+ return null;
170
+ }
171
+ const host = url.hostname.toLowerCase();
172
+ const segs = url.pathname.split('/').filter(Boolean);
173
+ const at = segs.findIndex((seg) => FULL_UUID_RE.test(seg));
174
+ if (at !== -1) {
175
+ // /app/<workspace>/docs/<uuid>: the canonical document URL.
176
+ const workspace =
177
+ segs[0] === 'app' && segs[2] === 'docs' && at === 3 ? decodeURIComponent(segs[1]) : null;
178
+ return { handle: segs[at].toLowerCase(), host, ...(workspace ? { workspace } : {}) };
179
+ }
180
+ // /app/projects/<id>: the numeric editor route, kept for old links and bookmarks.
181
+ if (segs[0] === 'app' && segs[1] === 'projects' && rowId(segs[2] ?? '') !== null) {
182
+ return { id: rowId(segs[2]), host };
183
+ }
184
+ return null;
185
+ }
186
+
187
+ // Free text with a handle in it ("the doc 7cd7…"): take the handle.
188
+ const m = UUID_RE.exec(s);
189
+ return m ? { handle: m[0].toLowerCase() } : null;
190
+ };
191
+
192
+ /** The web host each known API serves, for telling a user which environment a link belongs to. */
193
+ const WEB_FOR_API = {
194
+ 'api.workover.io': 'workover.io',
195
+ 'api.workover.dev': 'workover.dev',
196
+ 'api.workover.test': 'workover.test',
197
+ };
198
+
199
+ /**
200
+ * A sentence when a document link is for a different Workover than the one signed in to, else null.
201
+ *
202
+ * Only for hosts we know. A preview deploy's web and api hosts are not related by name, so they are
203
+ * left alone rather than guessed at — a wrong warning here would send someone to sign in somewhere
204
+ * they did not need to.
205
+ */
206
+ export const environmentMismatch = (ref, api) => {
207
+ if (!ref?.host || !api) return null;
208
+ let apiHost;
209
+ try {
210
+ apiHost = new URL(String(api)).hostname.toLowerCase();
211
+ } catch {
212
+ return null;
213
+ }
214
+ const signedInWeb = WEB_FOR_API[apiHost];
215
+ const linkHost = ref.host.replace(/^www\./, '');
216
+ const linkApi = Object.keys(WEB_FOR_API).find((k) => WEB_FOR_API[k] === linkHost);
217
+ if (!signedInWeb || !linkApi || signedInWeb === linkHost) return null;
218
+ return (
219
+ `That link is to ${linkHost}, but you are signed in to ${apiHost}. ` +
220
+ `Sign in there first (it replaces your current sign-in): WORKOVER_API=https://${linkApi} workover login`
221
+ );
222
+ };
223
+
224
+ /** The document argument a tool was given. `docId` is the schema's name; `url` / `doc` are what a
225
+ * model sometimes sends instead when it is holding a link, and refusing those would be pedantry. */
226
+ export const docArg = (args = {}) => args.docId ?? args.url ?? args.doc ?? args.link;
227
+
228
+ /** The message for a document argument that names no document at all. */
229
+ export const notADocErr = (got) =>
230
+ err(
231
+ `"${got ?? ''}" isn't a document id or a document URL. Pass the document link as the person gave it (https://workover.io/app/<workspace>/docs/<id>), the UUID at the end of it, or the numeric id.`,
232
+ );
233
+
234
+ /**
235
+ * A document's row id from a link, a UUID or a row id: `{ id }`, or `{ error }` (an MCP error
236
+ * result) saying what to do next.
237
+ *
238
+ * A link or UUID is resolved through `GET /project/doc/by-handle/<uuid>`, which applies the same
239
+ * access rules as reading the document by id. The failures are spelled out because an agent told
240
+ * only "error" goes looking for another way in, and on 2026-10-16 that meant reading the token file
241
+ * and grepping the Workover source for routes.
242
+ */
243
+ export const resolveDoc = async (api, value, apiBase) => {
244
+ const ref = docRef(value);
245
+ if (!ref) return { error: notADocErr(value) };
246
+ const mismatch = environmentMismatch(ref, apiBase);
247
+ if (mismatch) return { error: err(mismatch) };
248
+ if (ref.id) return { id: ref.id };
249
+ try {
250
+ const doc = await api(`/project/doc/by-handle/${encodeURIComponent(ref.handle)}`);
251
+ if (doc?.id) return { id: doc.id };
252
+ } catch (e) {
253
+ const message = String(e?.message || '');
254
+ if (/expired or was revoked/.test(message)) return { error: err(message) };
255
+ if (/\(410\)/.test(message))
256
+ return { error: err('That document is in the Trash. Ask the person to restore it in Workover.') };
257
+ if (e instanceof TypeError)
258
+ return { error: err(`Couldn't reach Workover${apiBase ? ` at ${apiBase}` : ''}.`) };
259
+ }
260
+ let where = '';
261
+ try {
262
+ where = apiBase ? ` (signed in to ${new URL(apiBase).host})` : '';
263
+ } catch {
264
+ where = '';
265
+ }
266
+ return {
267
+ error: err(
268
+ `No Workover document at that link that this sign-in can open${where}. Either it does not exist or this account has no access to it. Ask the person to check the link or share the document with them; do not look for another route.`,
269
+ ),
270
+ };
271
+ };
272
+
273
+ /** Kept for callers of the earlier helper: the row id, or null. */
274
+ export const resolveDocId = async (api, value) => (await resolveDoc(api, value)).id ?? null;
275
+
276
+ const decodeAttr = (v) =>
277
+ String(v ?? '')
278
+ .replace(/&quot;/g, '"')
279
+ .replace(/&#39;/g, "'")
280
+ .replace(/&lt;/g, '<')
281
+ .replace(/&gt;/g, '>')
282
+ .replace(/&amp;/g, '&');
283
+
284
+ const attrOf = (tag, name) => {
285
+ const m = new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, 'i').exec(tag);
286
+ return m ? decodeAttr(m[2] ?? m[3]) : null;
287
+ };
288
+
289
+ /**
290
+ * The images in a body, in reading order, one per distinct `src` (the CLI's `imagesInHtml`).
291
+ * The src is read off the rendered HTML byte for byte, because it is how the api identifies an image.
292
+ */
293
+ export const imagesInHtml = (html) => {
294
+ const out = [];
295
+ const bySrc = new Map();
296
+ for (const m of String(html || '').matchAll(/<img\b[^>]*>/gi)) {
297
+ const src = attrOf(m[0], 'src');
298
+ if (!src) continue;
299
+ const seen = bySrc.get(src);
300
+ if (seen) {
301
+ seen.count += 1;
302
+ continue;
303
+ }
304
+ const entry = { index: out.length + 1, src, alt: attrOf(m[0], 'alt') || '', count: 1 };
305
+ bySrc.set(src, entry);
306
+ out.push(entry);
307
+ }
308
+ return out;
309
+ };
310
+
132
311
  /** The error shown when a tool is handed something that isn't a numeric id. */
133
312
  export const badIdErr = (kind, got) =>
134
313
  err(
@@ -178,7 +357,18 @@ export function makeApi({ auth, fetchImpl = fetch }) {
178
357
  .catch(() => '');
179
358
  throw new Error(detail || 'This token isn’t allowed to do that.');
180
359
  }
181
- if (!res.ok) throw new Error(`Workover API error (${res.status}).`);
360
+ if (!res.ok) {
361
+ // The api's own sentence for a 4xx as well: "No image with that src is in this document"
362
+ // tells an agent what to do next, "Workover API error (404)" does not.
363
+ const detail =
364
+ res.status < 500
365
+ ? await res
366
+ .json()
367
+ .then((body) => (typeof body?.message === 'string' ? body.message : ''))
368
+ .catch(() => '')
369
+ : '';
370
+ throw new Error(`Workover API error (${res.status})${detail ? `: ${detail}` : '.'}`);
371
+ }
182
372
  return res.json();
183
373
  }
184
374
  const apiPost = (path, body) =>
@@ -198,7 +388,9 @@ export function makeApi({ auth, fetchImpl = fetch }) {
198
388
  export function makeDispatch({ auth, api, apiPost, fetchImpl = fetch, readFile }) {
199
389
  return async function dispatch(name, args = {}) {
200
390
  if (!auth)
201
- return err('Not signed in to Workover. Run `workover login` in your terminal first.');
391
+ return err(
392
+ 'Not signed in to Workover. Ask the person to run `workover login` in a terminal (or `npx -y @workover/cli@latest login`): it opens a browser for them to approve, and `--write` also allows direct edits. The next call here picks the sign-in up; no restart needed. Do not look for a token yourself.',
393
+ );
202
394
  try {
203
395
  if (name === 'workover_search_docs') {
204
396
  const { results = [] } = await api(
@@ -264,8 +456,9 @@ export function makeDispatch({ auth, api, apiPost, fetchImpl = fetch, readFile }
264
456
  );
265
457
  }
266
458
  if (name === 'workover_list_tabs') {
267
- const docId = rowId(args.docId);
268
- if (docId === null) return badIdErr('document', args.docId);
459
+ const doc = await resolveDoc(api, docArg(args), auth.api);
460
+ if (doc.error) return doc.error;
461
+ const docId = doc.id;
269
462
  const tabs = await api(`/project/doc/${docId}/tabs`);
270
463
  if (!Array.isArray(tabs) || !tabs.length)
271
464
  return text(
@@ -282,8 +475,9 @@ export function makeDispatch({ auth, api, apiPost, fetchImpl = fetch, readFile }
282
475
  );
283
476
  }
284
477
  if (name === 'workover_create_tab') {
285
- const docId = rowId(args.docId);
286
- if (docId === null) return badIdErr('document', args.docId);
478
+ const doc = await resolveDoc(api, docArg(args), auth.api);
479
+ if (doc.error) return doc.error;
480
+ const docId = doc.id;
287
481
  const title = String(args.title || '').trim();
288
482
  if (!title) return err('Provide a `title` for the new tab.');
289
483
  const parentId = args.parentId == null ? null : rowId(args.parentId);
@@ -298,8 +492,9 @@ export function makeDispatch({ auth, api, apiPost, fetchImpl = fetch, readFile }
298
492
  );
299
493
  }
300
494
  if (name === 'workover_read_doc') {
301
- const docId = rowId(args.docId);
302
- if (docId === null) return badIdErr('document', args.docId);
495
+ const doc = await resolveDoc(api, docArg(args), auth.api);
496
+ if (doc.error) return doc.error;
497
+ const docId = doc.id;
303
498
  const tabId = args.tabId == null ? null : rowId(args.tabId);
304
499
  if (args.tabId != null && tabId === null)
305
500
  return badIdErr('tab', args.tabId);
@@ -430,8 +625,9 @@ export function makeDispatch({ auth, api, apiPost, fetchImpl = fetch, readFile }
430
625
  if (name === 'workover_upload_image') {
431
626
  const p = String(args.path || '');
432
627
  if (!p) return err('Provide the local `path` to the image file.');
433
- const docId = rowId(args.docId);
434
- if (docId === null) return badIdErr('document', args.docId);
628
+ const doc = await resolveDoc(api, docArg(args), auth.api);
629
+ if (doc.error) return doc.error;
630
+ const docId = doc.id;
435
631
  let buf;
436
632
  try {
437
633
  buf = readFile(p);
@@ -454,11 +650,76 @@ export function makeDispatch({ auth, api, apiPost, fetchImpl = fetch, readFile }
454
650
  `Uploaded. Reference it in the document markdown:\n\n![${args.alt || 'screenshot'}](${url})`,
455
651
  );
456
652
  }
653
+ if (name === 'workover_list_images') {
654
+ const doc = await resolveDoc(api, docArg(args), auth.api);
655
+ if (doc.error) return doc.error;
656
+ const docId = doc.id;
657
+ const tabId = args.tabId == null ? null : rowId(args.tabId);
658
+ if (args.tabId != null && tabId === null) return badIdErr('tab', args.tabId);
659
+ const live = await api(
660
+ `/project/doc/${docId}/content${tabId === null ? '' : `?tabId=${tabId}`}`,
661
+ );
662
+ const images = imagesInHtml(live?.html || '');
663
+ if (!images.length)
664
+ return text(
665
+ `No images in ${live?.tab ? `the "${live.tab.title}" tab of ` : ''}document #${docId}.`,
666
+ );
667
+ for (const img of images) {
668
+ const meta = await api(
669
+ `/project/doc/${docId}/media/meta?src=${encodeURIComponent(img.src)}`,
670
+ );
671
+ img.filename = meta?.filename || '';
672
+ }
673
+ const tabs = Array.isArray(live?.tabs) ? live.tabs : [];
674
+ return text(
675
+ `Images in ${live?.tab ? `the "${live.tab.title}" tab of ` : ''}document #${docId}, in reading order. The file name is what WordPress gets on publish; pass the src to workover_set_image.\n\n` +
676
+ images
677
+ .map(
678
+ (i) =>
679
+ `${i.index}. ${i.filename}${i.count > 1 ? ` (appears ${i.count}×)` : ''}\n alt: ${i.alt || '(none)'}\n src: ${i.src}`,
680
+ )
681
+ .join('\n') +
682
+ (tabs.length
683
+ ? `\n\nThis document has ${tabs.length} tabs; pass tabId to list another: ${tabs.map((t) => `#${t.id} ${t.title}`).join(', ')}.`
684
+ : ''),
685
+ );
686
+ }
687
+ if (name === 'workover_set_image') {
688
+ const doc = await resolveDoc(api, docArg(args), auth.api);
689
+ if (doc.error) return doc.error;
690
+ const docId = doc.id;
691
+ const src = String(args.src || '');
692
+ if (!src) return err('Provide the image `src`, exactly as workover_list_images printed it.');
693
+ const filename = typeof args.filename === 'string' ? args.filename : undefined;
694
+ const alt = typeof args.alt === 'string' ? args.alt : undefined;
695
+ if (filename === undefined && alt === undefined)
696
+ return err('Provide `filename`, `alt` or both. Whichever is left out is kept.');
697
+ const res = await api(`/project/doc/${docId}/media`, {
698
+ method: 'PATCH',
699
+ headers: { 'content-type': 'application/json' },
700
+ body: JSON.stringify({
701
+ src,
702
+ ...(filename !== undefined ? { filename } : {}),
703
+ ...(alt !== undefined ? { alt } : {}),
704
+ syncDoc: true,
705
+ }),
706
+ });
707
+ const inDoc =
708
+ alt !== undefined && typeof res?.updatedInDoc === 'number'
709
+ ? res.updatedInDoc
710
+ ? ` Alt text set on ${res.updatedInDoc} image node(s) in the document.`
711
+ : ' The image already had that alt text, so the document was left as it was.'
712
+ : '';
713
+ return text(
714
+ `Updated: file name "${res?.filename}", alt "${res?.alt || ''}".${inDoc} The file name is what WordPress gets on the next publish.`,
715
+ );
716
+ }
457
717
  if (name === 'workover_edit_doc') {
458
718
  const md = String(args.markdown || '').trim();
459
719
  if (!md) return err('Provide the full revised document as `markdown`.');
460
- const docId = rowId(args.docId);
461
- if (docId === null) return badIdErr('document', args.docId);
720
+ const doc = await resolveDoc(api, docArg(args), auth.api);
721
+ if (doc.error) return doc.error;
722
+ const docId = doc.id;
462
723
  const tabId = args.tabId == null ? null : rowId(args.tabId);
463
724
  if (args.tabId != null && tabId === null)
464
725
  return badIdErr('tab', args.tabId);
@@ -479,8 +740,9 @@ export function makeDispatch({ auth, api, apiPost, fetchImpl = fetch, readFile }
479
740
  if (name === 'workover_propose_edit') {
480
741
  const md = String(args.markdown || '').trim();
481
742
  if (!md) return err('Provide the full revised document as `markdown`.');
482
- const docId = rowId(args.docId);
483
- if (docId === null) return badIdErr('document', args.docId);
743
+ const doc = await resolveDoc(api, docArg(args), auth.api);
744
+ if (doc.error) return doc.error;
745
+ const docId = doc.id;
484
746
  const tabId = args.tabId == null ? null : rowId(args.tabId);
485
747
  if (args.tabId != null && tabId === null)
486
748
  return badIdErr('tab', args.tabId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workover/mcp",
3
- "version": "0.8.1",
3
+ "version": "0.10.0",
4
4
  "description": "Workover MCP server — let Claude Code and other MCP clients read and cowork on your Workover documents.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "ScaleMath",